package com.socket.nio.server;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

import com.alibaba.fastjson.JSONObject;

public class MySocketServer {

    private int port;

    public MySocketServer(int port) {
        this.port = port;
    }

    public void serverSocket() throws IOException {
        ServerSocket serverSocket = new ServerSocket(this.port);
        Socket socket = null;
        boolean flag = true;
        InputStream is = null;
        while (flag) {
            socket = serverSocket.accept();
            is = socket.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int i = 0;
            while ((i = is.read()) != -1) {
                bos.write(i);
            }
            String name = "";
            if (bos.size() > 0) {
                JSONObject jsonObject = JSONObject.parseObject(bos.toString());
                name = jsonObject.getString("name");
                System.out.println("name=" + name);
            }
            bos.close();
            if (name.equals("111")) {
                flag = false;
            }
        }
        is.close();
        if (socket != null) {
            socket.close();
        }
        serverSocket.close();

    }


    public static void main(String[] args) {
        try {
            MySocketServer mySocketServer = new MySocketServer(8080);
            mySocketServer.serverSocket();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
